<?php
namespace app\controller;

use app\BaseController;
use app\middleware\Auth;
use app\model\ChaozhuoAivideo;
use app\model\ChaozhuoAlarm;
use app\model\ChaozhuoEquiment;
use app\model\ChaozhuoEquimentRealtime;
use app\model\ChaozhuoFace;
use app\model\ChaozhuoInspect;
use app\model\ChaozhuoInspectMonthtable;
use app\model\ChaozhuoInspectRepairtable;
use app\model\ChaozhuoInspectServicedtable;
use app\model\ChaozhuoInspectWeektable;
use app\model\ChaozhuoProject;
use app\model\ChaozhuoTowercycle;
use app\model\ChaozhuoUploadfile;
use app\model\ChaozhuoUser;
use GatewayWorker\Lib\Gateway;
use GuzzleHttp\Client;
use think\facade\Cache;
use think\facade\Filesystem;
use think\facade\Log;
use think\Request;

class WxController extends BaseController
{
    protected $middleware = [
        // 对所有方法应用 Auth 中间件，但排除 login 方法
        Auth::class => ['except' => ['login']]
    ];
    /* 获取云眸取流认证token */
    public function getYmToken(Request $request)
    {
        // Cache::delete('YmToken');
        $client = new Client();
        $url = 'https://api2.hik-cloud.com/oauth/token';
        $send = [
            "client_id" => env('ym_client_id'),
            "client_secret" => env('ym_client_secret'),
            "grant_type" => 'client_credentials',
        ];
        $access_token = Cache::get('YmToken');
        if ($access_token === null) {
            try {
                $response = $client->request('POST', $url, [
                    'form_params' => $send,
                ])->getBody();
                $data = json_decode($response, true);
                if (isset($data['access_token'])) {
                    $access_token = $data['access_token'];
                    Cache::set('YmToken', $access_token, 518400);
                } else {
                    return error('Failed to retrieve access token');
                }
            } catch (\GuzzleHttp\Exception\RequestException $e) {
                return fail('token fail');
            }
        }
        $client = new Client();
        $response = $client->get('https://api2.hik-cloud.com/v1/ezviz/account/info', [
            'headers' => [
                'Authorization' => 'Bearer ' . $access_token,
            ],
        ])->getBody();
        return success(json_decode($response, true)['data']);
    }
    /* 获取萤石云缓存 */
    public function getYsAccessToken(Request $request)
    {
        // Cache::delete('YS_AccessToken');
        $client = new Client();
        $url = 'https://open.ys7.com/api/lapp/token/get';
        $send = [
            "appKey" => env('YSappKey'),
            "appSecret" => env('YSappSecret'),
        ];
        $accessToken = Cache::get('YS_AccessToken');
        if ($accessToken === null) {
            try {
                $response = $client->request('POST', $url, [
                    'form_params' => $send,
                ])->getBody();
                $data = json_decode($response, true);
                if (isset($data['data']['accessToken'])) {
                    $accessToken = $data['data']['accessToken'];
                    Cache::set('YS_AccessToken', $accessToken, 518400);
                } else {
                    return error('Failed to retrieve access token');
                }
            } catch (\GuzzleHttp\Exception\RequestException $e) {
                return error('Request failed: ' . $e->getMessage());
            }
        }
        return success($accessToken);
    }
    /* 登录 */
    public function login(Request $request)
    {
        $authorization = $request->header('authorization');
        $where = [
            'account_number' => $request->post('account_number'),
            'password' => $request->post('password'),
        ];
        $user = ChaozhuoUser::where($where)->find();

        if ($user) {
            $user->token = $request->post('account_number');
            $user->save();
            $hidden = ['create_time', 'update_time', 'delete_time'];
            $user->hidden($hidden);
            Cache::set($user->token, $user, 86400);
            $user = Cache::get($user->token);
            return success($user);
        } else {
            return fail(null, '账号或密码错误');
        }
    }
    /* 项目列表 */
    public function projectList(Request $request)
    {
        $param = $request->param();
        $where = [];
        if ($request->has('pname', 'get', true)) {
            $pname = $request->param('pname');
            $where[] = ['pname', 'like', '%' . $param['pname'] . '%'];
        }
        if ($request->user->identity != 'admin') {
            $where[] = ['id', '=', $request->user->pid];
        }
        $list = ChaozhuoProject::where($where)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 设备列表 */
    public function equimentList(Request $request)
    {
        $param = $request->param();
        $user = $request->user;
        $where = [];
        // 检查是否有 name 参数
        if ($request->has('name', 'get', true)) {
            $name = $param['name'];
            // 使用闭包实现 orWhere 的逻辑
            $where[] = function ($query) use ($name) {
                $query->where('name', 'like', '%' . $name . '%')
                    ->whereOr('eid', 'like', '%' . $name . '%');
            };
        }
        // if ($request->has('name', 'get', true)) {
        //     $name = $request->param('name');
        //     $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        // }
        // if ($request->has('eid', 'get', true)) {
        //     $eid = $request->param('eid');
        //     $where[] = ['eid', 'like', '%' . $param['eid'] . '%'];
        // }
        $where[] = ['pid', '=', $request->param('pid')];
        $fields = ['id', 'name', 'eid', 'online', 'alarm_status', 'pname'];
        $list = ChaozhuoEquiment::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 设备详情页*/
    public function equimentInfo(Request $request)
    {
        $param = $request->param();
        $fields = ['online', 'alarm_status', 'tower_realtime_height', 'tower_realtime_amplitude', 'tower_realtime_rotation', 'tower_realtime_tilt_angle', 'tower_realtime_wind_speed', 'tower_realtime_weight', 'tower_realtime_torque', 'tower_realtime_work_cycle'];
        $ChaozhuoEquiment = ChaozhuoEquiment::where('eid', $param['eid'])->field($fields)->find();
        return success($ChaozhuoEquiment);
    }
    /* 设备实时画面*/
    public function equimentRealtimeVideo(Request $request)
    {
        $param = $request->param();
        // $fields = ["tower_video_address1", "tower_video_address1_name", "tower_video_address2", "tower_video_address2_name", "tower_video_address3", "tower_video_address3_name", "tower_video_address4", "tower_video_address4_name", "tower_video_address5", "tower_video_address5_name", "tower_video_address6", "tower_video_address6_name"];
        $fields = ['*'];
        $ChaozhuoEquiment = ChaozhuoEquiment::where('eid', $param['eid'])->field($fields)->find();
        return success($ChaozhuoEquiment);
    }
    /* 人脸信息 */
    public function faceList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        // if ($request->has('tower_start_time', 'get', true)) {
        //     $startTime = $request->param('tower_start_time');
        //     $where[] = ['tower_start_time', '>=', $startTime];
        // }
        $fields = ['*'];
        $list = ChaozhuoFace::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 添加周检 */
    public function addInspectWeektable(Request $request)
    {
        $param = $request->param();
        $ChaozhuoInspect = new ChaozhuoInspect;
        $ChaozhuoInspect->name = $param['name'];
        $ChaozhuoInspect->inspection_time = $param['inspection_time'];
        $ChaozhuoInspect->phone = $param['phone'];
        $ChaozhuoInspect->eid = $param['eid'];
        $ChaozhuoInspect->type = 1; //周检
        $rq = $ChaozhuoInspect->save();
        unset($param['eid']);
        // if ($request->has('id')) { //判断是否为添加
        //     $ChaozhuoInspectWeektable = ChaozhuoInspectWeektable::find($request->post('id'));
        // } else {
        //     $ChaozhuoInspectWeektable = new ChaozhuoInspectWeektable;
        // }
        $ChaozhuoInspectWeektable = new ChaozhuoInspectWeektable;
        foreach ($param as $key => $value) {
            $ChaozhuoInspectWeektable->$key = $value;
        }
        $ChaozhuoInspectWeektable->inspect_id = $ChaozhuoInspect->id;
        $rq = $ChaozhuoInspectWeektable->save();
        return success($ChaozhuoInspectWeektable);
    }
    /* 添加月检 */
    public function addInspectMonthtable(Request $request)
    {
        $param = $request->param();
        $ChaozhuoInspect = new ChaozhuoInspect;
        $ChaozhuoInspect->name = $param['name'];
        $ChaozhuoInspect->phone = $param['phone'];
        $ChaozhuoInspect->eid = $param['eid'];
        $ChaozhuoInspect->type = 2; //月
        $rq = $ChaozhuoInspect->save();
        unset($param['eid']);
        $ChaozhuoInspectMonthtable = new ChaozhuoInspectMonthtable;
        foreach ($param as $key => $value) {
            $ChaozhuoInspectMonthtable->$key = $value;
        }
        $ChaozhuoInspectMonthtable->inspect_id = $ChaozhuoInspect->id;
        $rq = $ChaozhuoInspectMonthtable->save();
        return success($ChaozhuoInspectMonthtable);
    }
    /* 添加检修 */
    public function addInspectRepairtable(Request $request)
    {
        $param = $request->param();
        $ChaozhuoInspect = new ChaozhuoInspect;
        $ChaozhuoInspect->name = $param['name'];
        $ChaozhuoInspect->inspection_time = $param['inspection_time'];
        $ChaozhuoInspect->phone = $param['phone'];
        $ChaozhuoInspect->eid = $param['eid'];
        $ChaozhuoInspect->type = 3; //检修
        $rq = $ChaozhuoInspect->save();
        unset($param['eid']);
        $ChaozhuoInspectRepairtable = new ChaozhuoInspectRepairtable;
        foreach ($param as $key => $value) {
            $ChaozhuoInspectRepairtable->$key = $value;
        }
        $ChaozhuoInspectRepairtable->inspect_id = $ChaozhuoInspect->id;
        $rq = $ChaozhuoInspectRepairtable->save();
        return success($ChaozhuoInspectRepairtable);
    }
    /* 添加报修 */
    public function addInspectServicetable(Request $request)
    {
        $param = $request->param();
        $ChaozhuoInspect = new ChaozhuoInspect;
        $ChaozhuoInspect->name = $param['name'];
        $ChaozhuoInspect->phone = $param['phone'];
        $ChaozhuoInspect->eid = $param['eid'];
        $ChaozhuoInspect->type = 4; //检修
        $rq = $ChaozhuoInspect->save();
        $ChaozhuoInspectServicedtable = new ChaozhuoInspectServicedtable;
        foreach ($param as $key => $value) {
            $ChaozhuoInspectServicedtable->$key = $value;
        }
        $ChaozhuoInspectServicedtable->inspect_id = $ChaozhuoInspect->id;
        $ChaozhuoEquiment = ChaozhuoEquiment::where('eid', $param['eid'])->find();
        $ChaozhuoInspectServicedtable->pid = $ChaozhuoEquiment->pid;
        $ChaozhuoInspectServicedtable->pname = $ChaozhuoEquiment->pname;
        $ChaozhuoInspectServicedtable->ename = $ChaozhuoEquiment->name;
        $rq = $ChaozhuoInspectServicedtable->save();
        return success($ChaozhuoInspectServicedtable);
    }
    /* 塔机工作循环 */
    public function towerCycleList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        if ($request->has('tower_start_time', 'get', true)) {
            $startTime = $request->param('tower_start_time');
            $where[] = ['tower_start_time', '>=', $startTime];
        }
        if ($request->has('tower_end_time', 'get', true)) {
            $endTime = $request->param('tower_end_time');
            $where[] = ['tower_end_time', '<=', $endTime];
        }

        $fields = ['*'];
        $list = ChaozhuoTowercycle::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        foreach ($list as &$record) {
            // 格式化start_time和end_time, 去掉年份和秒数
            $record['tower_start_time'] = date('m-d H:i', strtotime($record['tower_start_time']));
            $record['tower_end_time'] = date('m-d H:i', strtotime($record['tower_end_time']));
        }
        return pageReturn($list);
    }
    public function uploadFile(Request $request)
    {
        $upload_url = env('UPLOAD_URL', true);
        $post = $request->post();
        $file = request()->file('file');
        //$文件名
        $fileName = $file->getOriginalName();
        $date = date('Y_m_d', time()); //当天日期
        $fileOssName = time() . $fileName; //阿里云文件名
        $ext = $file->getOriginalExtension(); //文件扩展名
        $ext = 'wx';
        // $ossurl = config('filesystem.disks.aliyun.url');
        // 上传本地服务器
        $res = Filesystem::disk('public')->putFileAs($ext . '/' . $date, $file, $fileOssName); //按照文件类型分类
        $res = stripslashes($res); //去除转义字符
        $fileurl = 'https://' . $upload_url . '/' . $res;
        //地址存入数据库
        $upload = new ChaozhuoUploadfile;
        $upload->url = $fileurl;
        $upload->filename = $fileOssName;
        $upload->save();

        return success($fileurl);
    }
    public function userInfo(Request $request)
    {
        return success($request->user);
    }
    public function aiVideoList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        if ($request->has('start_time', 'get', true)) {
            $startTime = $request->param('start_time');
            $where[] = ['start_time', '>=', $startTime];
        }
        if ($request->has('end_time', 'get', true)) {
            $end_time = $request->param('end_time');
            $where[] = ['end_time', '<=', $end_time];
        }
        $fields = ['*'];
        $list = ChaozhuoAivideo::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        foreach ($list as &$record) {
            // 格式化start_time和end_time, 去掉年份和秒数
            $record['start_time'] = date('m-d H:i', strtotime($record['start_time']));
            $record['end_time'] = date('m-d H:i', strtotime($record['end_time']));
        }
        return pageReturn($list);
    }
    /* 报警记录 */
    public function alarmList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        if ($request->has('start_time', 'get', true)) {
            $startTime = $request->param('start_time');
            $where[] = ['create_time', '>=', $startTime];
        }
        if ($request->has('end_time', 'get', true)) {
            $end_time = $request->param('end_time');
            $where[] = ['create_time', '<=', $end_time];
        }
        if ($request->has('alarm_level', 'get', true)) {
            $alarm_level = $request->param('alarm_level');
            $where[] = ['alarm_level', '=', $alarm_level];
        }
        if ($request->has('alarm_item', 'get', true)) {
            $alarm_item = $request->param('alarm_item');
            $where[] = ['alarm_item', '=', $alarm_item];
        }
        $fields = ['*'];
        $list = ChaozhuoAlarm::where($where)->field($fields)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    public function inspectList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        $where[] = ['type', '=', $request->param('type')];
        // 检查并添加结束时间条件
        // if ($request->has('tower_start_time', 'get', true)) {
        //     $startTime = $request->param('tower_start_time');
        //     $where[] = ['tower_start_time', '>=', $startTime];
        // }
        $fields = ['*'];
        $list = ChaozhuoInspect::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 删除检修记录 */
    public function reInspect(Request $request)
    {
        $id = $request->param('id');
        $Resource = ChaozhuoInspect::find($id);
        // $rq = $Resource->destroy($id);
        $rq = $Resource->force()->delete(); //直接删除
        if ($rq) {
            return success($request);
        }
        return success($ChaozhuoEquiment);
    }
    /* 周检表格 */
    public function inspectWeektable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('inspect_id')];
        $fields = ['*'];
        $list = ChaozhuoInspectWeektable::where($where)->field($fields)->find();

        $listArray = $list->toArray(); // 如果 $list 是对象，则首先转换为数组

        $filteredData = [];
        $towerInspectResult = [];

        foreach ($listArray as $key => $value) {
            if (strpos($key, 'tower_inspect_no') === 0 && strpos($key, '_result') !== false) {
                // 如果键名符合要求，则添加到 towerInspectResult 数组中
                $towerInspectResult[$key] = $value;
            } else {
                // 否则直接复制到 filteredData 中
                $filteredData[$key] = $value;
            }
        }
        $filteredData['tower_inspect_result'] = $towerInspectResult;
        return success($filteredData);
    }
    /* 月检表格 */
    public function inspectMonthtable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('inspect_id')];
        $fields = ['*'];
        $list = ChaozhuoInspectMonthtable::where($where)->field($fields)->find();

        $listArray = $list->toArray(); // 如果 $list 是对象，则首先转换为数组

        $filteredData = [];
        $towerInspectResult = [];

        foreach ($listArray as $key => $value) {
            if (strpos($key, 'tower_inspect_no') === 0) {
                // 如果键名符合要求，则添加到 towerInspectResult 数组中
                $towerInspectResult[$key] = $value;
            } else {
                // 否则直接复制到 filteredData 中
                $filteredData[$key] = $value;
            }
        }
        $filteredData['tower_inspect_result'] = $towerInspectResult;
        return success($filteredData);
    }
    /* 检修表格 */
    public function inspectRepairtable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('inspect_id')];
        $fields = ['*'];
        $list = ChaozhuoInspectRepairtable::where($where)->field($fields)->find();

        $listArray = $list->toArray(); // 如果 $list 是对象，则首先转换为数组

        $filteredData = [];
        $towerInspectResult = [];

        foreach ($listArray as $key => $value) {
            if (strpos($key, 'tower_inspect_no') === 0) {
                // 如果键名符合要求，则添加到 towerInspectResult 数组中
                $towerInspectResult[$key] = $value;
            } else {
                // 否则直接复制到 filteredData 中
                $filteredData[$key] = $value;
            }
        }
        $filteredData['tower_inspect_result'] = $towerInspectResult;
        return success($filteredData);
    }
    /* 报修表格 */
    public function inspectServicetable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('inspect_id')];
        $fields = ['*'];
        $ChaozhuoInspectServicedtable = ChaozhuoInspectServicedtable::where($where)->field($fields)->find();
        return success($ChaozhuoInspectServicedtable);
    }
    /* 处理报修 */
    public function dealwithServicetable(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['inspect_id', '=', $request->param('id')];
        $fields = ['*'];
        $ChaozhuoInspect = ChaozhuoInspect::find($request->param('id'));
        $ChaozhuoInspectServicedtable = ChaozhuoInspectServicedtable::where($where)->find();
        $ChaozhuoInspect->is_dealwith = 1;
        $ChaozhuoInspect->save();
        $ChaozhuoInspectServicedtable->is_dealwith = 1;
        $rq = $ChaozhuoInspectServicedtable->save();
        return success($rq);
    }

    /* 请求下载AI报警视频 */
    public function downloadAlarmAiVideo(Request $request)
    {
        $param = $request->param();
        return success(true);
    }
    /* 删除AI视频记录 */
    public function reAiVideo(Request $request)
    {
        $id = $request->param('id');
        $Resource = ChaozhuoAivideo::find($id);
        // $rq = $Resource->destroy($id);
        $rq = $Resource->force()->delete(); //直接删除
        if ($rq) {
            return success($request);
        }
        return success($ChaozhuoEquiment);
    }
    /* 删除报警记录 */
    public function reAlarm(Request $request)
    {
        $id = $request->param('id');
        $Resource = ChaozhuoAlarm::find($id);
        // $rq = $Resource->destroy($id);
        $rq = $Resource->force()->delete(); //直接删除
        if ($rq) {
            return success($request);
        }
        return success($ChaozhuoEquiment);
    }

    /* 实时数据 */
    public function realtimeList(Request $request)
    {
        $param = $request->param();
        $where = [];
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', 'like', '%' . $param['eid'] . '%'];
        }
        if ($request->has('ename', 'get', true)) {
            $ename = $request->param('ename');
            $where[] = ['ename', 'like', '%' . $param['ename'] . '%'];
        }
        if ($request->has('pname', 'get', true)) {
            $pname = $request->param('pname');
            $where[] = ['pname', 'like', '%' . $param['pname'] . '%'];
        }
        if ($request->has('start_time', 'get', true)) {
            $startTime = $request->param('start_time');
            $where[] = ['create_time', '>=', $startTime];
        }
        if ($request->has('end_time', 'get', true)) {
            $end_time = $request->param('end_time');
            $where[] = ['create_time', '<=', $end_time];
        }
        $fields = ['*'];
        $list = ChaozhuoEquimentRealtime::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);
    }
    /* 报修提醒 */
    public function inspectServiceRemind(Request $request)
    {
        $user = $request->user;
        $identity = $request->user->identity;
        $param = $request->param();
        $where = [];
        $where[] = ['is_dealwith', '=', 0];
        if ($identity != 'admin') {
            $where[] = ['pid', '=', $request->user->pid];
        }
        $fields = ['*'];
        $list = ChaozhuoInspectServicedtable::where($where)->field($fields)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        // return success($user);
        return pageReturn($list);
    }
    /* EXCEL */
    public function exportCSV(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        if ($request->has('tower_start_time', 'get', true)) {
            $startTime = $request->param('tower_start_time');
            $where[] = ['tower_start_time', '>=', $startTime];
        }
        if ($request->has('tower_end_time', 'get', true)) {
            $endTime = $request->param('tower_end_time');
            $where[] = ['tower_end_time', '<=', $endTime];
        }

        $fields = ['*'];
        $list = ChaozhuoTowercycle::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        $list = $list->toArray();
        // return success($list['data']);
        // return pageReturn($list);
        // 设置导出文件名
        $fileName = 'export_' . date('YmdHis') . '.csv';
        // $fileName = 'export_' . date('YmdHis') . '.xls';
        // 设置 HTTP 头信息
        header('Content-Type: text/csv');
        // header('Content-Type: text/xls');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        // 打开输出缓冲区
        $fp = fopen('php://output', 'w');
        // 写入表头
        fputcsv($fp, ['设备ID', '开始时间', '结束时间', '起始高度', '起始幅度', '起始回转角度', '起始吊重', '结束高度', '结束幅度', '结束回转角度', '结束吊重']);
        // 查询数据库数据
        // $dataList = Db::name('your_table')->select();
        // 写入数据
        foreach ($list['data'] as $item) {
            fputcsv($fp, [
                $item['eid'],
                $item['tower_start_time'],
                $item['tower_end_time'],
                $item['tower_start_height'],
                $item['tower_start_amplitude'],
                $item['tower_start_rotation'],
                $item['tower_start_load'],
                $item['tower_end_height'],
                $item['tower_end_amplitude'],
                $item['tower_end_rotation'],
                $item['tower_end_load'],
            ]);
        }
        // 关闭输出缓冲区
        fclose($fp);
        exit();
    }
    public function exportTowercycle(Request $request)
    {
        $param = $request->param();
        $where = [];
        $where[] = ['eid', '=', $request->param('eid')];
        // 检查并添加结束时间条件
        if ($request->has('tower_start_time', 'get', true)) {
            $startTime = $request->param('tower_start_time');
            $where[] = ['tower_start_time', '>=', $startTime];
        }
        if ($request->has('tower_end_time', 'get', true)) {
            $endTime = $request->param('tower_end_time');
            $where[] = ['tower_end_time', '<=', $endTime];
        }

        $fields = ['*'];
        $list = ChaozhuoTowercycle::where($where)->field($fields)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        $list = $list->toArray();
        // return success($list['data']);
        // return pageReturn($list);
        // 设置导出文件名
        $fileName = 'export_' . date('YmdHis') . '.csv';
        // $fileName = 'export_' . date('YmdHis') . '.xls';
        // 设置 HTTP 头信息
        header('Content-Type: text/csv');
        // header('Content-Type: text/xls');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        // 打开输出缓冲区
        $fp = fopen('php://output', 'w');
        // 写入表头
        fputcsv($fp, ['设备ID', '开始时间', '结束时间', '起始高度', '起始幅度', '起始回转角度', '起始吊重', '结束高度', '结束幅度', '结束回转角度', '结束吊重']);
        // 查询数据库数据
        // $dataList = Db::name('your_table')->select();
        // 写入数据
        foreach ($list['data'] as $item) {
            fputcsv($fp, [
                $item['eid'],
                $item['tower_start_time'],
                $item['tower_end_time'],
                $item['tower_start_height'],
                $item['tower_start_amplitude'],
                $item['tower_start_rotation'],
                $item['tower_start_load'],
                $item['tower_end_height'],
                $item['tower_end_amplitude'],
                $item['tower_end_rotation'],
                $item['tower_end_load'],
            ]);
        }
        // 关闭输出缓冲区
        fclose($fp);
        exit();
    }
    /* GatewayWorker-请求下载AI视频 */
    public function downloadAiVideo(Request $request)
    {
        $param = $request->all();
        $uid = $param['eid'];
        $resultArray = ['token' => 'czdz', 'mtype' => 2, 'channel' => (int) $param['channel'], 'eid' => $param['eid'], 'aid' => $param['aid']];
        Log::write('uid: ' . $uid, 'chaozhuoTCP');
        Log::write(json_encode($resultArray), 'chaozhuoTCP');
        Gateway::$registerAddress = '0.0.0.0:1290'; //设置第二个woker
        Gateway::sendToUid($uid, json_encode($resultArray));
        sleep(5); //5s等待时间
        // $client_id = Gateway::getClientIdByUid($uid);
        // Log::write($client_id, 'chaozhuoTCP');
        $where[] = ['id', '=', $request->param('aid')];
        $ChaozhuoAivideo = ChaozhuoAivideo::where($where)->find();
        return success($ChaozhuoAivideo);
    }
}
